import sys
from main import app
from backend.security import datastore
from backend.models import db, Role, User
from werkzeug.security import generate_password_hash
from datetime import datetime
import traceback

with app.app_context():
    db.create_all()

    # Define role data
    roles_data = [
        {"category": "Secondary", "name": "root", "description": "User who manages the system"},
        {"category": "Primary", "name": "coach", "description": "User who teaches and manages health"},
        {"category": "Primary", "name": "member", "description": "User who works on health"},
    ]
    
    # Create roles
    try:
        for role in roles_data:
            datastore.find_or_create_role(
                name=role["name"],
                description=role["description"]
            )   
        print(f"{len(roles_data)} roles created.")
        db.session.commit()
    except Exception as e:
        with open("error_initial_data.txt", "w") as file:
            file.write(f"ERROR: {e}\n")
        rootprint(f"ERROR: {e}")
        sys.exit("Exiting the program due to an exception.\n{e}")

    # Define user data
    users_data = [
        {"email": "root@g.com", "username": "root", "password": "r", "roles": ["root"]},
        {"email": "coach@g.com", "username": "coach", "password": "c", "roles": ["coach"]},
        {"email": "member@g.com", "username": "mem", "password": "m", "roles": ["member"]},
    ]

    # Create users
    try:
        for user in users_data:
            if not datastore.find_user(email=user["email"]):
                datastore.create_user(
                    email=user["email"],
                    username=user.get("username", user["username"]),
                    password=generate_password_hash(user["password"]),
                    roles=user["roles"]
                )
        print(f"{len(users_data)} users created.")
        db.session.commit()

    except Exception as e:
        with open("error_initial_data.txt", "w") as file:
            # Capture the traceback details including the line number
            file.write(f"ERROR: {e}\n")
            file.write(f"Traceback details:\n{traceback.format_exc()}\n")
        print(f"ERROR: {e}")
        print(f"Traceback details:\n{traceback.format_exc()}")
        sys.exit("Exiting the program due to an exception.\n{e}")
